use std::collections::HashMap;
use std::ops::Add;
use chrono::{DateTime, Local, TimeDelta};
use yewdux::Dispatch;
use crate::business::page::fragment::im_session_list_view::{SessionAction, SessionListState};
use crate::db::dao::im_message_dao::query_hot_message_total;
use crate::db::dao::im_session_dao::{incr_hot_message_num, set_hot_message_num};
use crate::db::db::Db;
use crate::db::service::im_session_service::ImSessionService;

pub struct CheckHotMessageService;

impl CheckHotMessageService {

    pub fn check_hot_message_total(dispatch: Dispatch<SessionListState>, user_id: String, start_date: DateTime<Local>) {
        log::info!("check hot message total, {:?}", start_date);
        let db = Db::open();
        let hot_messages = query_hot_message_total(db.clone(), &user_id, start_date);
        let hot_message_map = hot_messages.iter().fold(HashMap::new(), |mut map, message| {
            *map.entry(message.session_id).or_insert(0) += message.size;
            map
        });
        log::info!("check hot message total, {:?}", hot_messages);
        dispatch.apply(SessionAction::IncrementHotMessages(hot_message_map));


        let session_service = ImSessionService;
        let _start_time = Local::now().add(TimeDelta::days(-14));
        let mut session_list = session_service.query(&user_id, 0, 1000);

        for session in session_list {
            let mut is_have = false;
            for hot_message_total in hot_messages.iter() {
                if hot_message_total.session_id == session.id.clone().unwrap() {
                    is_have = true;

                    if hot_message_total.size != session.hot_message_total as usize {
                        incr_hot_message_num(db.clone(), session.id.unwrap(), hot_message_total.size as i32);
                        break;
                    }
                }
                
            }
            if !is_have && session.hot_message_total > 0{
                log::info!("check hot message total change, {:?}", session);
                set_hot_message_num(db.clone(), session.id.unwrap(), 0);
            }
        }
    }
}